<template>
  <el-drawer v-model="drawerVisible" :z-index="1000" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}角色`">
    <el-form
      ref="roleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
      v-if="drawerProps.row"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="drawerProps.row!.roleName" placeholder="请填写角色名称" clearable></el-input>
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input v-model="drawerProps.row!.description" placeholder="请填写描述" clearable></el-input>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select
          :disabled="drawerProps.row?.users !== undefined && drawerProps.row!.users > 0"
          v-model="drawerProps.row!.status"
          placeholder="请选择状态"
          clearable
        >
          <el-option v-for="item in status" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="权限">
        <el-tree ref="treeRef" show-checkbox node-key="id" :data="permissionList" :props="defaultProps" style="width: 100%" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="_colse">取消</el-button>
      <el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="RoleDrawer">
import { ref, reactive, onMounted, nextTick } from "vue";
import { status } from "@/utils/serviceDict";
import { ElMessage, FormInstance } from "element-plus";
import { Role } from "@/api/interface";
import { getPermissionTree, getRoleDtl } from "@/api/modules/role";
const treeRef = ref();
const defaultProps = {
  children: "children",
  label: "label"
};
const permissionList = ref([]);
const rules = reactive({
  roleName: [{ required: true, message: "请填写角色名称" }],
  status: [{ required: true, message: "请选择状态" }]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Role.ResRoleList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  resetTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});
// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
  if (drawerProps.value.title !== "新增") {
    const { result } = await getRoleDtl({ roleId: drawerProps.value.row!.roleId as string });

    let permissionTree: any = [];
    result &&
      getFlatPermissionTree(result.permissionTree).forEach(item => {
        if (item.selected === "1") {
          permissionTree.push(item.permissionId);
        }
      });
    permissionTree.forEach((item: string) => {
      nextTick(() => {
        let node = treeRef.value.getNode(item);
        if (node.isLeaf) {
          //判断是否是子节点
          treeRef.value.setChecked(node, true);
        }
      });
    });
  }
};

// 提交数据（新增/编辑）
const roleFormRef = ref<FormInstance>();
/**
 * 关闭弹窗
 */
const _colse = () => {
  drawerVisible.value = false;
  roleFormRef.value && roleFormRef.value.resetFields();
};
/**
 * 提交信息
 */
const handleSubmit = () => {
  roleFormRef.value!.validate(async valid => {
    if (!valid) return;
    const permissionTree = [...treeRef.value.getCheckedKeys(), ...treeRef.value.getHalfCheckedKeys()];
    const permissionList = permissionTree.map((item: string) => {
      return {
        permissionId: item
      };
    });
    if (permissionTree.length <= 0) {
      ElMessage.warning({ message: `请选择权限` });
      return false;
    }
    try {
      await drawerProps.value.api!({ ...drawerProps.value.row, permissionList });
      ElMessage.success({ message: `${drawerProps.value.title}角色成功！` });
      drawerProps.value.title === "新增" ? drawerProps.value.resetTableList!() : drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};
/**
 * 匹配权限树数据
 */
const matchPermissionItem = (list: Role.ResPermission[]): any => {
  return list.map((item: any) => {
    if (item.children) {
      item.children = matchPermissionItem(item.children);
    }
    return {
      id: item.permissionId,
      label: item.permissionName,
      children: item.children
    };
  });
};
/**
 * 展开权限树
 */
const getFlatPermissionTree = (permissionTree: Role.ResPermission[]): Role.ResPermission[] => {
  let permissionList: Role.ResPermission[] = JSON.parse(JSON.stringify(permissionTree));
  return permissionList.flatMap((item: Role.ResPermission) => [
    item,
    ...(item.children ? getFlatPermissionTree(item.children) : [])
  ]);
};

onMounted(async () => {
  const { permissionTree } = await getPermissionTree();
  permissionList.value = matchPermissionItem(permissionTree);
});
defineExpose({
  acceptParams
});
</script>
